/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.Investiture;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Club;
import pt.iasd.youthshelter.datamodel.ProgressiveClass;
import pt.iasd.youthshelter.datamodel.service.ProgressiveClassController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=ProgressiveClassController.class)
public class ProgressiveClassJpaController implements Serializable, ProgressiveClassController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(ProgressiveClass progressiveClass) {
        if (progressiveClass.getInvestitureList() == null) {
            progressiveClass.setInvestitureList(new ArrayList<Investiture>());
        }
        if (progressiveClass.getClubList() == null) {
            progressiveClass.setClubList(new ArrayList<Club>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<Investiture> attachedInvestitureList = new ArrayList<Investiture>();
            for (Investiture investitureListInvestitureToAttach : progressiveClass.getInvestitureList()) {
                investitureListInvestitureToAttach = em.getReference(investitureListInvestitureToAttach.getClass(), investitureListInvestitureToAttach.getId());
                attachedInvestitureList.add(investitureListInvestitureToAttach);
            }
            progressiveClass.setInvestitureList(attachedInvestitureList);
            List<Club> attachedClubList = new ArrayList<Club>();
            for (Club clubListClubToAttach : progressiveClass.getClubList()) {
                clubListClubToAttach = em.getReference(clubListClubToAttach.getClass(), clubListClubToAttach.getId());
                attachedClubList.add(clubListClubToAttach);
            }
            progressiveClass.setClubList(attachedClubList);
            em.persist(progressiveClass);
            for (Investiture investitureListInvestiture : progressiveClass.getInvestitureList()) {
                investitureListInvestiture.getProgressiveClassList().add(progressiveClass);
                investitureListInvestiture = em.merge(investitureListInvestiture);
            }
            for (Club clubListClub : progressiveClass.getClubList()) {
                clubListClub.getProgressiveClassList().add(progressiveClass);
                clubListClub = em.merge(clubListClub);
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(ProgressiveClass progressiveClass) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            ProgressiveClass persistentProgressiveClass = em.find(ProgressiveClass.class, progressiveClass.getId());
            List<Investiture> investitureListOld = persistentProgressiveClass.getInvestitureList();
            List<Investiture> investitureListNew = progressiveClass.getInvestitureList();
            List<Club> clubListOld = persistentProgressiveClass.getClubList();
            List<Club> clubListNew = progressiveClass.getClubList();
            List<Investiture> attachedInvestitureListNew = new ArrayList<Investiture>();
            for (Investiture investitureListNewInvestitureToAttach : investitureListNew) {
                investitureListNewInvestitureToAttach = em.getReference(investitureListNewInvestitureToAttach.getClass(), investitureListNewInvestitureToAttach.getId());
                attachedInvestitureListNew.add(investitureListNewInvestitureToAttach);
            }
            investitureListNew = attachedInvestitureListNew;
            progressiveClass.setInvestitureList(investitureListNew);
            List<Club> attachedClubListNew = new ArrayList<Club>();
            for (Club clubListNewClubToAttach : clubListNew) {
                clubListNewClubToAttach = em.getReference(clubListNewClubToAttach.getClass(), clubListNewClubToAttach.getId());
                attachedClubListNew.add(clubListNewClubToAttach);
            }
            clubListNew = attachedClubListNew;
            progressiveClass.setClubList(clubListNew);
            progressiveClass = em.merge(progressiveClass);
            for (Investiture investitureListOldInvestiture : investitureListOld) {
                if (!investitureListNew.contains(investitureListOldInvestiture)) {
                    investitureListOldInvestiture.getProgressiveClassList().remove(progressiveClass);
                    investitureListOldInvestiture = em.merge(investitureListOldInvestiture);
                }
            }
            for (Investiture investitureListNewInvestiture : investitureListNew) {
                if (!investitureListOld.contains(investitureListNewInvestiture)) {
                    investitureListNewInvestiture.getProgressiveClassList().add(progressiveClass);
                    investitureListNewInvestiture = em.merge(investitureListNewInvestiture);
                }
            }
            for (Club clubListOldClub : clubListOld) {
                if (!clubListNew.contains(clubListOldClub)) {
                    clubListOldClub.getProgressiveClassList().remove(progressiveClass);
                    clubListOldClub = em.merge(clubListOldClub);
                }
            }
            for (Club clubListNewClub : clubListNew) {
                if (!clubListOld.contains(clubListNewClub)) {
                    clubListNewClub.getProgressiveClassList().add(progressiveClass);
                    clubListNewClub = em.merge(clubListNewClub);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = progressiveClass.getId();
                if (findProgressiveClass(id) == null) {
                    throw new NonexistentEntityException("The progressiveClass with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            ProgressiveClass progressiveClass;
            try {
                progressiveClass = em.getReference(ProgressiveClass.class, id);
                progressiveClass.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The progressiveClass with id " + id + " no longer exists.", enfe);
            }
            List<Investiture> investitureList = progressiveClass.getInvestitureList();
            for (Investiture investitureListInvestiture : investitureList) {
                investitureListInvestiture.getProgressiveClassList().remove(progressiveClass);
                investitureListInvestiture = em.merge(investitureListInvestiture);
            }
            List<Club> clubList = progressiveClass.getClubList();
            for (Club clubListClub : clubList) {
                clubListClub.getProgressiveClassList().remove(progressiveClass);
                clubListClub = em.merge(clubListClub);
            }
            em.remove(progressiveClass);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<ProgressiveClass> findProgressiveClassEntities() {
        return findProgressiveClassEntities(true, -1, -1);
    }

    @Override
    public List<ProgressiveClass> findProgressiveClassEntities(int maxResults, int firstResult) {
        return findProgressiveClassEntities(false, maxResults, firstResult);
    }

    private List<ProgressiveClass> findProgressiveClassEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ProgressiveClass.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public ProgressiveClass findProgressiveClass(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(ProgressiveClass.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getProgressiveClassCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ProgressiveClass> rt = cq.from(ProgressiveClass.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
